//
//  StoresNearbyGoodsViewController.m
//  TerritoryShopkeeper
//
//  Created by 李小龙 on 2017/12/19.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "StoresNearbyGoodsViewController.h"
#import "ClassifyTitleView.h"
#import "StoresNearbyModel.h"
#import "StoresGoodsTableCollectionViewCell.h"
#import "GoodsDetailViewController.h"
#import "SearchCacheViewController.h"
#import "GoodStandardView.h"
#import "SKUManager.h"
#import "ShopcartOrderViewController.h"
#import "StoresShopcartView.h"

@interface StoresNearbyGoodsViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UISearchBarDelegate, UIScrollViewDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UIImageView *headerImageView;
@property (weak, nonatomic) IBOutlet UILabel *storeNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;

@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UILabel *allPriceLabel;
@property (weak, nonatomic) IBOutlet UIButton *accountButton;

@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UISearchBar *searchBar;

@property (nonatomic, strong) ClassifyTitleView *titleView;
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray<StoresNearbyModel *> *firstArr;
@property (nonatomic, assign) NSInteger index;

@property (nonatomic, strong) NSMutableArray<StoresGoodModel *> *cartArr;
@property (nonatomic, strong) StoresShopcartView *cartView;

@end

@implementation StoresNearbyGoodsViewController

static NSString *storeGoodsCollectionItemIdentifier = @"storeGoodsCollectionItemIdentifier";
#pragma mark - Get
- (UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] init];
        [_searchView.layer setCornerRadius:14];
        _searchView.clipsToBounds = YES;
        [_searchView setBackgroundColor:[UIColor whiteColor]];
    }
    return _searchView;
}
- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] init];
        _searchBar.delegate = self;
        [_searchBar setTintColor:[UIColor blueColor]];
        _searchBar.backgroundImage = [UIImage imageWithColor:[UIColor whiteColor]];
        //[_searchBar changeLeftPlaceholder:@"搜索你想要的"];
        _searchBar.placeholder = @"搜索你感兴趣的商品";
        
        UITextField *searchField = [_searchBar valueForKey:@"searchField"];
        searchField.mj_h = 28;
        [searchField.layer setCornerRadius:14];
        //[searchField.layer setBorderWidth:0.5];
        [searchField.layer setBorderColor:[UIColor lightGrayColor].CGColor];
        searchField.layer.masksToBounds = YES;
        searchField.font = TextPingFangFontSize(14);
        
    }
    return _searchBar;
}
- (NSMutableArray<StoresNearbyModel *> *)firstArr {
    if (!_firstArr) {
        _firstArr = [[NSMutableArray alloc] init];
    }
    return _firstArr;
}
- (NSMutableArray<StoresGoodModel *> *)cartArr {
    if (!_cartArr) {
        _cartArr = [[NSMutableArray alloc] init];
    }
    return _cartArr;
}
- (StoresShopcartView *)cartView {
    if (!_cartView) {
        _cartView = [StoresShopcartView createShopcartView:self.cartArr];
    }
    return _cartView;
}
- (ClassifyTitleView *)titleView {
    if (!_titleView) {
        _titleView = [[ClassifyTitleView alloc] init];
    }
    return _titleView;
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.itemSize = CGSizeMake(ScreenWidth-self.titleView.width, self.titleView.height);
         _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.pagingEnabled = YES;
        _collectionView.alwaysBounceHorizontal = YES;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.bounces = NO;
        _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        
        [_collectionView registerNib:[UINib nibWithNibName:@"StoresGoodsTableCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:storeGoodsCollectionItemIdentifier];
    }
    return _collectionView;
}
#pragma mark - IBAction
- (IBAction)accountButtonAction:(id)sender {
    // 跳转结算页
    ShopcartOrderViewController *shopcartVC = [[ShopcartOrderViewController alloc] init];
    shopcartVC.type = ShopcartOrderTypeNearby;
    //MARK:测试
    NSString *gaids = @"", *numbers = @"";
    for (NSInteger i = 0; i < self.cartArr.count; i++) {
        StoresGoodModel *model = self.cartArr[i];
        if (i == 0) {
            gaids = model.gaid;
            numbers = model.gcount;
        } else {
            gaids = [NSString stringWithFormat:@"%@,%@",gaids,model.gaid];
            numbers = [NSString stringWithFormat:@"%@,%@",numbers,model.gcount];
        }
    }
    shopcartVC.gaids = gaids;
    shopcartVC.numbers = numbers;
    
    [self.navigationController pushViewController:shopcartVC animated:YES];
}
- (IBAction)cartButtonAction:(id)sender {
    [self.cartView setCartArrayWith:self.cartArr isShow:YES];
    [self.cartView showView];
}
#pragma mark - UIViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configureNavigation];
    [self createUI];
    
    [self updateHeaderData];
    [self getNetData];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hideNavigationController];
    [self setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.titleView.frame = CGRectMake(0, self.headerView.bottom, 84, self.view.height-self.headerView.height-self.bottomView.height);
    self.collectionView.frame = CGRectMake(self.titleView.right, self.titleView.top, self.view.width - self.titleView.right, self.titleView.height);
}
#pragma mark - Action
- (void)configureNavigation {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClick)];
    
    [self.searchView addSubview:self.searchBar];
    self.searchView.frame = CGRectMake(0, 0, ScreenWidth - 15 * 4 - 28 * 2, 28);
    self.searchBar.frame = CGRectMake(0, 0, self.searchView.width, 28);
    self.navigationItem.titleView = self.searchView;
}
- (void)rightItemClick {
    [self disMissSelf];
}
- (void)createUI {
    [self.headerImageView setCircleWithColor:[UIColor whiteColor] borderWidth:2 cornerRadius:self.headerImageView.width/2.0];
    
    [self.view addSubview:self.titleView];
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.cartView];
    [self.view bringSubviewToFront:self.bottomView];
    
    __weak typeof(self) weakSelf = self;
    self.titleView.block = ^(NSInteger index) {
        NSLog(@"%ld", (long)index);
        [weakSelf scrollIndexOrSelectIndex:index];
        [weakSelf.collectionView scrollRectToVisible:CGRectMake(0, weakSelf.collectionView.height * index, weakSelf.collectionView.width, weakSelf.collectionView.height) animated:YES];
    };
    
    self.cartView.ShopcartBlock = ^(NSInteger type, StoresGoodModel *model) {
        for (StoresNearbyModel *nearbyModel in weakSelf.firstArr) {
            if ([nearbyModel.scid isEqualToString:model.scid]) {
                for (StoresGoodModel *goodsModel in nearbyModel.goods) {
                    if ([goodsModel.gid isEqualToString:model.gid]) {
                        for (GoodsAttributePriceModel *priceModel in goodsModel.goodsattribute) {
                            if ([priceModel.gaid isEqualToString:model.gaid]) {
                                priceModel.selectNumber = model.gcount;
                                [weakSelf reloadUI];
                                break;
                            }
                        }
                        break;
                    }
                }
                break;
            }
        }
    };
}
- (void)reloadUI {
    [self.titleView setupRedPointWithTitleArr:[self getFirstStr:self.firstArr] withIndex:self.index];
    [self.collectionView reloadData];
    [self updateBottomData];
}
- (NSMutableArray *)getFirstStr:(NSArray *)arr {
    
    NSMutableArray *titleArr = [NSMutableArray array];
    for (StoresNearbyModel *model in self.firstArr) {
        ClassifyTitleModel *titleModel = [ClassifyTitleModel mj_objectWithKeyValues:model];
        [titleArr addObject:titleModel];
    }
    
    return titleArr;
}

- (void)updateHeaderData {
    [self.headerImageView sd_setImageWithURL:GetUrl(self.storeModel.simg) placeholderImage:PlaceholderImageHeader];
    
    [self.storeNameLabel setText:self.storeModel.sname];
    
    [self.distanceLabel setText:[NSString stringWithFormat:@"距离：%.2fkm",self.storeModel.sdistance.doubleValue]];
}
- (void)updateBottomData {
    double allPrice = 0;
    for (StoresGoodModel *goodModel in self.cartArr) {
        allPrice += goodModel.gprice.doubleValue * goodModel.gcount.integerValue;
    }
    NSString *allPriceStr = [NSString stringWithFormat:@"¥%.2f",allPrice];
    [self.allPriceLabel setText:[allPriceStr replacePriceSuffix]];
    
    //[self.accountButton setTitle:[NSString stringWithFormat:@"结算(%d)",4] forState:UIControlStateNormal];
}
- (void)addStoreNearbyCart:(StoresGoodModel *)goodModel {
    //MARK:测试 添加到附近门店购物车
    for (StoresGoodModel *model in self.cartArr) {
        if ([model.gid isEqualToString:goodModel.gid]) {
            [self.cartArr removeObject:model];
            break;
        }
    }
    if (goodModel.count.integerValue != 0) {
        [self.cartArr addObject:goodModel];
    }
    [self reloadUI];
}
- (void)addCartArrayObject:(StoresGoodModel *)object firstModel:(StoresNearbyModel *)firstModel {
    [GoodStandardView showGoodStandardViewWithTitle:object.gname
                                              price:object.gprice
                                            pgprice:@""
                                              count:@""
                                           imageURL:object.gimg
                              goodAttributeModelArr:[SKUManager getSelectOriginDataArr:object.attribute withPriceSkuArr:object.goodsattribute withGaid:object.gaid]
                        goodsAttributePriceModelArr:object.goodsattribute
                                               type:GoodStandardViewTypeNearby
                                          needReset:NO
                                              block:^(NSInteger buttonIndex, NSMutableArray *arr, GoodsAttributePriceModel *priceModel, NSString *count) {
          // arr已选属性 priceModel已选的属性Model count已选数量 object商品Model firstModel当前分类Model
//          if (![object.gaid isEqualToString:priceModel.gaid] || ![object.count isEqualToString:count]) {
//
//              object.gaid = priceModel.gaid;
//              object.count = count;
              if (TextIsNotNil(priceModel.gaid)) {
                  BOOL isContain = NO;
                  for (StoresGoodModel *model in self.cartArr) {
                      if ([model.gaid isEqualToString:priceModel.gaid]) {
                          isContain = YES;
                          if (count.integerValue == 0) {
                              [self.cartArr removeObject:model];
                          } else {
                              model.gcount = count;
                          }
                          break;
                      }
                  }
                  if (!isContain && count > 0) {
                      StoresGoodModel *model = [StoresGoodModel mj_objectWithKeyValues:object];
                      model.gaid = priceModel.gaid;
                      model.gcount = count;
                      
                      NSString *selectAtt;
                      for (GoodAttributeValueModel *attModel in arr) {
                          if (!TextIsNotNil(selectAtt)) {
                              selectAtt = attModel.taname;
                          } else {
                              selectAtt = [NSString stringWithFormat:@"%@;%@",selectAtt,attModel.taname];
                          }
                      }
                      model.selectAttribute = selectAtt;
                      
                      [self.cartArr addObject:model];
                  }
                  [self reloadUI];
              }
//          }
                                              }];
}

#pragma mark - 网络请求
- (void)getNetData {
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc] init];
    [parameter setObject:self.storeModel.sid forKey:@"sid"];
    
    __block typeof(self) blockSelf = self;
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Shop_Get_Class parameters:parameter success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [blockSelf.firstArr removeAllObjects];
            for (NSDictionary *dataDic in responseObject[@"data"]) {
                StoresNearbyModel *model = [StoresNearbyModel mj_objectWithKeyValues:dataDic];
                [blockSelf.firstArr addObject:model];
            }
            
            [blockSelf reloadUI];
        } else {
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}
#pragma mark - UISearchBarDelegate
- (void)gotoSearchVC {
    SearchCacheViewController *searchVC = [[SearchCacheViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    SearchCacheViewController *searchCacheVC = [[SearchCacheViewController alloc] init];
    searchCacheVC.type = SearchCacheViewControllerTypeForSearch;
    [self.navigationController pushViewController:searchCacheVC animated:YES];
    return NO;
}

#pragma mark -- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.firstArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    __block typeof(self) blockSelf = self;
    StoresGoodsTableCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:storeGoodsCollectionItemIdentifier forIndexPath:indexPath];
    
    StoresNearbyModel *firstModel = [self.firstArr safeObjectAtIndex:indexPath.row];
    [cell setTableViewData:firstModel.goods];
    cell.block = ^(ClickType type, NSInteger count, NSInteger index) {
        switch (type) {
            case ClickTypeNormal:
            {
                StoresGoodModel *model = [firstModel.goods safeObjectAtIndex:index];
                if (!model.isshelves) {
                    [MBProgressHUD showError:blockSelf.view title:@"该商品已下架" code:@"" animated:YES];
                    return;
                }
                GoodsDetailViewController *goodsDetailVC = [[GoodsDetailViewController alloc] init];
                goodsDetailVC.type = GoodsDetailViewControllerTypeForNearby;
                goodsDetailVC.gid = model.gid;
                [blockSelf.navigationController pushViewController:goodsDetailVC animated:YES];
            } break;
            case ClickTypeSub: case ClickTypeText:
            {
                if (firstModel.number.integerValue + count > 0) {
                    firstModel.number = [NSString stringWithFormat:@"%ld",(long)(firstModel.number.integerValue + count)];
                } else {
                    firstModel.number = @"0";
                }

                StoresGoodModel *model = [firstModel.goods safeObjectAtIndex:index];
                if (model.count.integerValue + count > 0) {
                    model.count = [NSString stringWithFormat:@"%ld",(long)(model.count.integerValue + count)];
                } else {
                    model.count = @"0";
                }
                
                [blockSelf addStoreNearbyCart:model];
            } break;
            case ClickTypeAdd:
            {
                StoresGoodModel *model = [firstModel.goods safeObjectAtIndex:index];
                [blockSelf addCartArrayObject:model firstModel:firstModel];
            } break;
            case ClickTypeChoose:
            {
                StoresGoodModel *model = [firstModel.goods safeObjectAtIndex:index];
                if (!TextIsNotNil(model.count)) {
                    model.count = @"0";
                }
                [blockSelf addCartArrayObject:model firstModel:firstModel];
            } break;
            default:
                break;
        }
    };
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(self.view.width - self.titleView.width, self.titleView.height);
}
#pragma mark - UIScrollViewDeleagte
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView != self.collectionView) {
        return;
    }
    CGFloat y = scrollView.contentOffset.y;
    CGFloat page = y / self.titleView.height;
    NSInteger index = (page + 0.3) / 1;
    [self.titleView setToShowIndex:index withAnimation:YES];
    [self scrollIndexOrSelectIndex:index];
}

- (void)scrollIndexOrSelectIndex:(NSInteger)index {
    self.index = index;
    //    ClassifyFirstModel *firstModel = [self.firstArr safeObjectAtIndex:index];
    //    [self getSecondClass:firstModel.gcid];
}
#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
